import 'dart:math';

import 'package:flutter/material.dart';
import 'package:ui_templates/introduction_animation_page/introduction_animation_page.dart';
import 'package:ui_templates/model/home_list.dart';
import "app_theme.dart";

class HomePage extends StatefulWidget {
  HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

//能根据系统的明暗主题切换颜色，然后他为了尽可能真实模拟了获取数据的过程，使用了futureBuilder
//当然这东西是可以嵌套的，然后APPBar实际上是自己写的,然后他有一个animationController控制页面切换的动画
class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  int columnCount = 2;
  late AnimationController _controller;

  Future<bool> getData() async {
    await Future.delayed(const Duration(milliseconds: 10), () {
      print("getData finished");
    });
    return true;
  }

  @override
  void initState() {
    _controller =
        AnimationController(vsync: this, duration: const Duration(seconds: 4));
    _controller.forward();
    super.initState();
  }

  Widget createAppbar() {
    var lightMode = MediaQuery.of(context).platformBrightness;
    bool isLightMode = (lightMode == Brightness.light);
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Container(
        height: AppBar().preferredSize.height,
        // color: Colors.grey,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 8, left: 8),
              child: Container(
                // color: Colors.green,
                width: AppBar().preferredSize.height - 8,
                height: AppBar().preferredSize.height - 8,
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.center,
                child: const Text("FLUTTER UI", style: AppTheme.title),
              ),
            ),
            Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              child: IconButton(
                onPressed: () {
                  setState(() {
                    columnCount = columnCount == 1 ? 2 : 1;
                  });
                },
                icon: Icon(
                  columnCount == 2 ? Icons.dashboard : Icons.view_agenda,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var lightMode = MediaQuery.of(context).platformBrightness;
    bool isLightMode = (lightMode == Brightness.light);

    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: FutureBuilder(
            future: getData(),
            builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
              if (snapshot.hasError) {
                return Text(snapshot.error.toString());
              } else {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Container(
                      height: 100,
                      child: const Center(
                        child: CircularProgressIndicator(),
                      ));
                } else {
                  bool res = snapshot.data as bool;
                  if (!res) {
                    return const Text("getData failed");
                  } else {
                    Random random = Random(100);
                    return Column(
                      children: [
                        createAppbar(),
                        Expanded(
                          child: GridView(
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisSpacing: 10,
                              mainAxisSpacing: 10,
                              crossAxisCount: columnCount,
                              childAspectRatio: 3 / 2,
                            ),
                            children: HomeList.homeList.map((ele) {
                              int idx = HomeList.homeList
                                  .indexWhere((item) => item == ele);
                              return AnimatedBuilder(
                                  animation: _controller,
                                  builder: (context, child) {
                                    return Opacity(
                                      opacity: (Tween<double>(begin: 0, end: 1)
                                              .chain(CurveTween(
                                                  curve: Curves.fastOutSlowIn))
                                              .chain(CurveTween(
                                                curve: Interval(
                                                    (idx /
                                                        HomeList
                                                            .homeList.length),
                                                    (idx + 1) /
                                                        HomeList
                                                            .homeList.length),
                                              ))
                                              .animate(_controller))
                                          .value,
                                      child: Material(
                                        //不理解好像没用
                                        child: InkWell(
                                          highlightColor:
                                              Colors.blueGrey.withOpacity(.6),
                                          hoverColor:
                                              Colors.blueGrey.withOpacity(.6),
                                          onTap: () {
                                            FocusScope.of(context)
                                                .requestFocus(FocusNode());
                                            Navigator.of(context).push(
                                                MaterialPageRoute(
                                                    builder: (context) {
                                              return IntroductionAnimationPage();
                                            }));
                                          },
                                          child: Container(
                                            decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              image: DecorationImage(
                                                image:
                                                    AssetImage(ele.imagePath),
                                                fit: BoxFit.cover,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    );
                                  });
                            }).toList(),
                          ),
                        ),
                      ],
                    );
                  }
                }
              }
            }),
      ),
    );
  }
}
